import columnsData, { ColumnsItem } from './data'
import React from 'react';
import { Modal, Form, Input, Popconfirm, message, Descriptions, Button, Select } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { getWithdrawApplyList, handleWithdrawApply } from './service'
import TableTitle from '@/components/TableTitle';
import 'moment/locale/zh-cn';
import moment from 'moment';

const { Option } = Select;
const { TextArea } = Input;

export default () => {
  // 控制详情弹框的显示与隐藏
  const [withdrawRecordModal, setWithdrawRecordModal] = React.useState(false)
  // 控制拒绝原因弹框的显示与隐藏
  const [refuseModal, setRefuseModal] = React.useState(false)
  // 表头赋值
  const columns: ProColumns<ColumnsItem>[] = columnsData
  // 原因表单
  const reasonFormRef: any = React.createRef();
  // 储存当前查看数据
  const [withdrawRecord, setWithdrawRecord] = React.useState<ColumnsItem | undefined>(undefined)

  // 拒绝原因文本域
  const [isShowTextArea, setIsShowTextArea] = React.useState(false)

  // 定义操作单元格
  const columnsRender = (text: any, record: ColumnsItem) => {
    return [
      <a key='check'
        onClick={() => {
          console.log(record)
          handleDetails(record)
        }
        }
      >
        查看
      </a >
    ]
  }

  // 定义金额单元格
  const amountRender = (text: any) => [
    <p
      key='amount'
      style={{ textAlign: 'right', margin: 0 }}
    >
      {typeof text === 'number' ? text.toFixed(6) : null}
    </p>
  ]

  // 列渲染样式赋值
  columns.forEach(item => {
    item.dataIndex === 'withdrawAmt' ? item.render = amountRender : undefined
    item.valueType === 'option' ? item.render = columnsRender : undefined
  })

  /**
   * 查看按钮回调
   * @param txNO 流水号
   */
  const handleDetails = (record: ColumnsItem) => {
    setWithdrawRecord(record)
    setWithdrawRecordModal(true)
  }

  // 批准 是按钮回调
  const confirm = async () => {
    let userInfo = window.localStorage.getItem('userInformation')
      ? JSON.parse(window.localStorage.getItem('userInformation'))
      : null;

    let params = {
      reqNo: withdrawRecord?.reqNo,
      status: '1',
      operator: userInfo.sysUser.empName
    }
    console.log(params);

    let data = await handleWithdrawApply(params)
    console.log(data);
    if (data) {
      // 表格重刷新
      reloadRef.current?.reload()
      // 提醒成功
      message.success('已批准');
      setWithdrawRecordModal(false)
    } else {
      // 表格重刷新
      reloadRef.current?.reload()
      setWithdrawRecordModal(false)

    }
  }

  // 拒绝按钮回调
  const handleIsRefuse = () => {
    setRefuseModal(true)
  }
  // 选择拒绝原因
  const handleChange = (value: string) => {
    if (value === '1') {
      setIsShowTextArea(true)
    } else (
      isShowTextArea ? setIsShowTextArea(false) : null
    )
  }

  // 拒绝表单提交
  const handleRefuseOk = () => {
    // 表单验证
    reasonFormRef.current.validateFields().then(async () => {
      // 获取新增表单的值
      var reponse = reasonFormRef.current?.getFieldsValue()
      let userInfo = window.localStorage.getItem('userInformation')
        ? JSON.parse(window.localStorage.getItem('userInformation'))
        : null;
      console.log(reponse);
      const { refusalCause, refusal } = reponse
      let params = {
        reqNo: withdrawRecord?.reqNo,
        status: '2',
        operator: userInfo.sysUser.empName,
        reason: refusal ? refusal : refusalCause
      }
      let res = await handleWithdrawApply(params)
      if (res) {
        // 重置表单
        reasonFormRef.current.resetFields();
        // 表格重刷新
        reloadRef.current?.reload()
        // 关闭模态框
        setRefuseModal(false)
        setWithdrawRecordModal(false)
      }
    }).catch(() => { })
  }

  // Table action 的引用，便于自定义触发
  const reloadRef = React.useRef<ActionType>();

  return (
    <div>
      {/* 表格 */}
      <ProTable<ColumnsItem>
        scroll={{ x: 900 }}
        bordered
        headerTitle={<TableTitle title='提现审批' />}
        columns={columns}
        actionRef={reloadRef}
        // 请求的数据
        request={
          async params => {
            let res = await getWithdrawApplyList({ ...params, pageNum: params.current, sign: 1 })
            console.log(res);
            return {
              data: res.body.list,
              total: res.body.total,
            }
          }
        }
        // 本地储存表格列的显示参数
        columnsState={{
          persistenceKey: 'withdrawApplyList',
          persistenceType: 'localStorage',
        }}
        // 每行表格的key
        rowKey="reqNo"
        // 搜索表单布局配置
        search={{
          labelWidth: 'auto',
        }}
        // 分页相关配置
        pagination={{
          // 初始页面数据条数
          pageSize: 10,
        }}
        dateFormatter="string"
      />
      <Modal
        title="拒绝原因"
        visible={refuseModal}
        centered
        onOk={handleRefuseOk}
        onCancel={() => setRefuseModal(false)}
      >
        <Form
          name="basic"
          wrapperCol={{ span: 24 }}
          initialValues={{ remember: true }}
          autoComplete="off"
          ref={reasonFormRef}
        >
          <Form.Item
            key="refusalCause"
            name="refusalCause"
            rules={[{
              required: true,
              message: '请选择拒绝原因'
            }]}
          >

            <Select
              placeholder="请选择拒绝原因"
              style={{ width: '100%' }}
              onChange={handleChange}
            >
              <Option value="账户异常">账户异常</Option>
              <Option value="法币汇款失败">法币汇款失败</Option>
              <Option value="1">其他</Option>
            </Select>
          </Form.Item>
          {
            isShowTextArea ?
              <Form.Item
                key="refusal"
                name="refusal"
                rules={[{
                  required: true,
                  whitespace: true,
                  message: '请选择拒绝原因'
                }]}
              >
                <TextArea rows={3} maxLength={100} placeholder="请输入拒绝原因" />
              </Form.Item> : null
          }
        </Form>
      </Modal>
      <Modal
        title='提现详情'
        width={1000}
        centered
        visible={withdrawRecordModal}
        footer={
          <Button
            type="primary"
            htmlType="submit"
            onClick={() => setWithdrawRecordModal(false)}
          >
            确认
          </Button>}
        onCancel={() => setWithdrawRecordModal(false)}
      >
        <Descriptions
          column={{ xxl: 4, xl: 4, lg: 4, md: 3, sm: 2, xs: 1 }}
        >
          <Descriptions.Item label="提现客户">{withdrawRecord?.custNo}</Descriptions.Item>
          <Descriptions.Item label="客户类别">{withdrawRecord?.custType === 'C' ? '商户' : '会员'}</Descriptions.Item>
          <Descriptions.Item label="申请日期">{withdrawRecord?.reqTime}</Descriptions.Item>
          <Descriptions.Item label="汇率">{withdrawRecord?.exgRate}</Descriptions.Item>
          <Descriptions.Item label="提现方式">{withdrawRecord?.withdrawMethod === '0' ? '链钱包' : '法币银行账户'}</Descriptions.Item>
          <Descriptions.Item label="提现账号">{withdrawRecord?.withdrawAcctNo}</Descriptions.Item>
          {
            withdrawRecord?.withdrawMethod === '0' ?
              <Descriptions.Item label="目标钱包">{withdrawRecord?.chainWalletUrl} </Descriptions.Item> :
              <Descriptions.Item label="目标账号">{withdrawRecord?.acctNo} </Descriptions.Item>
          }
          <Descriptions.Item label="用户名"> {withdrawRecord?.custName}</Descriptions.Item>
          {
            withdrawRecord?.status === '1' ?
              <Descriptions.Item label="交易流水">{withdrawRecord?.txNo}</Descriptions.Item> :
              null
          }
          <Descriptions.Item label="审批状态">
            {
              withdrawRecord?.status === '0' ?
                '待处理' :
                withdrawRecord?.status === '1' ?
                  '已批准' :
                  withdrawRecord?.status === '2' ?
                    '已拒绝' : null
            }
          </Descriptions.Item>
          <Descriptions.Item label="提现金额">{withdrawRecord?.withdrawAmt?.toFixed(6)}</Descriptions.Item>
          <Descriptions.Item label="提现币别">{withdrawRecord?.withdrawalCcy} </Descriptions.Item>
          <Descriptions.Item label="手续费">{withdrawRecord?.fee?.toFixed(6)}</Descriptions.Item>
          <Descriptions.Item label="手续费币别">{withdrawRecord?.feeCcy} </Descriptions.Item>
          <Descriptions.Item label="预计到账金额">{withdrawRecord?.amt?.toFixed(6)}</Descriptions.Item>
          <Descriptions.Item label="到账币别">{withdrawRecord?.inAcctCcy} </Descriptions.Item>
          {
            withdrawRecord?.status !== '0' ?
              <>
                <Descriptions.Item label="审批人">{withdrawRecord?.operator}</Descriptions.Item>
                <Descriptions.Item label="审批时间">{withdrawRecord?.withdrawTime}</Descriptions.Item>
              </> :
              <div>
                <Popconfirm
                  title="是否批准本次提现?"
                  onConfirm={confirm}
                  okText="是"
                  cancelText="否"
                >
                  <a key='check'
                    style={{ marginRight: 30 }}
                  >
                    批准
                  </a >
                </Popconfirm>
                <a key='check'
                  onClick={() => handleIsRefuse()}
                >
                  拒绝
                </a >
              </div>
          }
          {
            withdrawRecord?.status === '2' ?
              <Descriptions.Item label="拒绝原因"> {withdrawRecord?.reason}</Descriptions.Item> : null
          }
        </Descriptions>
      </Modal>
    </div>
  );
};